package com.qf.dao.impl;

import com.qf.dao.GoodsDao;
import com.qf.pojo.Goods;
import com.qf.pojo.PageBean;
import com.qf.utils.DBtools;
import com.qf.utils.SQL;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * Created by Administrator on 2021/10/25.
 */
public class GoodsDaoImpl implements GoodsDao {

    QueryRunner queryRunner = new QueryRunner(DBtools.getDataSource());

    @Override
    public List<Goods> selectAll(int cid, int level, PageBean pageBean) {
        try {
            StringBuffer sql = new StringBuffer("select" + SQL.GOODS + "from goods where ");//
            if (level == 1) {
                sql.append("cat_id=?");
            } else if (level == 2) {
                sql.append("cat_cat_id=?");
            } else if (level == 3) {
                sql.append("cat_cat_id2=?");
            }
            sql.append(" limit ?,?");
            BeanListHandler<Goods> bean = new BeanListHandler<>(Goods.class);
            //(当前页-1)*每页行数
            int p1 = (pageBean.getPage() - 1) * pageBean.getRowsPerPage();
            //每页行数
            int p2 = pageBean.getRowsPerPage();
            return queryRunner.query(sql.toString(), bean, cid, p1, p2);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public int getAllRows(int cid, int level) {
        StringBuffer sql =new StringBuffer("SELECT COUNT(*) FROM goods WHERE ");
        if(level==1)
            sql.append("cat_id=?");
        else if(level==2)
            sql.append("cat_cat_id=?");
        else if(level==3)
            sql.append("cat_cat_id2=?");
        try {
            //long--int
            //Long--Integer
            //int--Integer--Object-->(Integer)-->拆箱int
            Long res = queryRunner.query(sql.toString(), new ScalarHandler<Long>(), cid);
            return res.intValue();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public Goods selectOne(int gid) {
        try {
            return queryRunner.query("select " + SQL.GOODS + "from goods where g_id=?", new BeanHandler<Goods>(Goods.class), gid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}
